const API = require('../../../utils/api.js');
const FormatUtil = require('../../../utils/util.js');
const TOAST = require('../../../utils/toast.js');
const AJAX = require('../../../utils/ajax.js')
// 引入腾讯地图
const qqMapWxUtil = require('../../../utils/qqMapWxUtil.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bookkeepingId: '',
    bookkeepingObj: {},
    updateShow: false,
    // 标记点
    markers: [],
    imageHost: API.api.imageHost,
    tempFilePaths: '',
    loading:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // 获取到记账id,判断是从哪个页面跳转过来的
    if (options.form === 'index') {
      console.log(`从记账页面跳转过来的！！！携带的id为：`, options.bookkeepingid)
      this.setData({
        bookkeepingId: options.bookkeepingid
      })
      // 获取用户记账信息
      this.getBookkeepingById(options.bookkeepingid);
    } else if(options.form === 'address'){
      let bookkeepingObj = wx.getStorageSync('bookkeepingObj')
      bookkeepingObj.address = options.address
      bookkeepingObj.addressDetail = options.addressDetail
      this.setData({
        bookkeepingObj: bookkeepingObj,
        updateShow: true
      })
      this.geocoder(options.address + options.addressDetail)
    } else{
      console.log(`来自其他消息` + options.form)
    }
  },
  /**
   * 显示保存
   */
  updateShowData: function() {
    let bookkeepingObj = this.data.bookkeepingObj;
    if (!this.data.updateShow) {
      // 格式化金额信息Int
      let money = FormatUtil.intFormatMoney(this.data.bookkeepingObj.moneyView)
      console.log(money)
      bookkeepingObj.moneyView = money
    } else {
      // 格式化金额信息String
      let money = FormatUtil.formatMoney(this.data.bookkeepingObj.moneyView)
      bookkeepingObj.moneyView = money
      console.log(money)
    }
    
    this.setData({
      updateShow: !this.data.updateShow,
      bookkeepingObj:bookkeepingObj
    })
  },
  /**
   * 填写备注
   */
  textareaRemark:function(e) {
    console.log(`获取到数据了`,e.detail.value)
    let bookkeepingObj = this.data.bookkeepingObj;
    bookkeepingObj.remarks = e.detail.value
    this.setData({
      bookkeepingObj:bookkeepingObj
    })
  },
  inputMoney:function(e) {
    console.log(`获取到数据了`, e.detail.value)
    let bookkeepingObj = this.data.bookkeepingObj;
    bookkeepingObj.moneyView = e.detail.value
    this.setData({
      bookkeepingObj: bookkeepingObj
    })
  },
  /**
   * 更新保存数据
   */
  updateData: function() {
    let that = this
    console.log('这里是保存数据的')
    let requestUrl = API.api.bookkeepings + '/' + this.data.bookkeepingObj.id;
    // 金额格式化
    let requestData = this.data.bookkeepingObj
    requestData.money = Number(requestData.moneyView) * 100;
    requestData.imageUrl = JSON.stringify(requestData.imageUrl)
    this.setData({
      loading:true
    })
    AJAX.putRequest(requestUrl,requestData).then(response => {
      // that.updateShowData()
      that.setData({
        loading:false
      })
      wx.switchTab({
        url: '/pages/index/index'
      })
    });
    
  },
  /**
   * 删除数据
   */
  deleteData: function() {
    console.log(`准备删除一条数据`)
    let that = this
    let requestUrl = API.api.bookkeepings + '/' + this.data.bookkeepingObj.id
    this.setData({
      loading:true
    })
    AJAX.delRequest(requestUrl).then(response => {
      console.log(`删除成功，返回主页面`)
      that.setData({
        loading:false
      })
      wx.switchTab({
        url: '/pages/index/index'
      })
    })
  },
  /**
   * 上传图片
   */
  uploadImag: function(e) {
    let that = this
    let imagePath = "";
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      success: function(res) {
        console.log(`获取到list`, res.tempFiles)
        const tempFiles = res.tempFiles;
        that.setData({
          tempFilePaths: tempFiles[0].path
        })
        let requestUrl = API.api.uploadFile + '/bookkeeping/bookkeeping'
        for (var i = 0; i < tempFiles.length;i++) {
          if (tempFiles[i].size > 1048576) {
            TOAST.showToastSuccess('图片大于1M')
            continue;
          }
          that.setData({
            loading:true
          })
          wx.uploadFile({
            url: requestUrl,
            filePath: tempFiles[i].path,
            name: 'file',
            header: {
              "Authorization": wx.getStorageSync('token')
            },
            success: function (res) {
              console.log(`这边是小程序上传文件返回回来的数据信息`)
              let resData = JSON.parse(res.data)
              let bookkeepingObj = that.data.bookkeepingObj;
              if (resData.code == 200) {
                console.log(`index:` + e.currentTarget.dataset.index)
                let index = e.currentTarget.dataset.index
                console.log(`imageUrl:` + bookkeepingObj.imageUrl.length)
                if(bookkeepingObj.imageUrl.length >= 2) {
                  index > bookkeepingObj.imageUrl ? bookkeepingObj.imageUrl.push(resData.data) : bookkeepingObj.imageUrl[index] = resData.data
                } else{
                  bookkeepingObj.imageUrl.push(resData.data)
                }
                that.setData({
                  bookkeepingObj: bookkeepingObj
                })
              }
              console.log(`bookkeepingObj:`, that.data.bookkeepingObj)
            },complete() {
              that.setData({
                loading:false
              })
            }
          })
        }
      }
    })
  },
  /**
   * 预览图片
   */
  previewImage:function(e) {
    let imageUrl = [];
    this.data.bookkeepingObj.imageUrl.forEach(item => {
      imageUrl.push(this.data.imageHost + item)
    })
    console.log(e.currentTarget.dataset.imageUrl)
    console.log(e.currentTarget.dataset.imageurl)
    console.log(`这个是当前的url:` + this.data.imageHost + e.currentTarget.dataset.imageurl)
    wx.previewImage({
      current: this.data.imageHost + e.currentTarget.dataset.imageurl,
      urls: imageUrl,
    })
  },
  /**
   * 跳转到gps定位
   */
  gotoAddress: function(e) {
    // 缓存对于的数据信息
    wx.setStorageSync('bookkeepingObj', this.data.bookkeepingObj)
    wx.navigateTo({
      url: '../address/address?form=bookkeepingDetail&address=' + this.data.bookkeepingObj.address + '&addressDetail=' + this.data.bookkeepingObj.addressDetail,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {},

  /**
   * 获取用户记账信息
   */
  getBookkeepingById: function(bookkeepingId) {
    let that = this;
    let requestUrl = API.api.bookkeepings + '/' + bookkeepingId;
    this.setData({
      loading:true
    })
    AJAX.getRequest(requestUrl).then(response => {
      let resultData = response.data
      resultData.createTimeView = FormatUtil.formatTime(new Date(resultData.createTime))
      resultData.moneyView = FormatUtil.formatMoney(resultData.money / 100)
      resultData.imageUrl = resultData.imageUrl ? JSON.parse(resultData.imageUrl) : []
      that.setData({
        bookkeepingObj: resultData,
        loading:false
      })
      // TODO 这里后期加判断，如果位置为空则重新定位还是什么的 通过位置定位信息
      that.geocoder(resultData.address + resultData.addressDetail)
    })
  },
  /**
   *调用腾讯地图显示位置信息
   * latitude:纬度
   * longitude：经度
   */
  reverseGeocoder: function(latitude, longitude) {
    let that = this
    let location = {}
    location.latitude = latitude;
    location.longitude = longitude;
    qqMapWxUtil.reverseGeocoder(location).then(response => {
      console.log(`从腾讯文档中获取到的地图坐标是：`, response)
      that.setData({
        markers: response.markers
      })
    })
  },
  /**
   * 调用腾讯地图进行定位
   * address:地址信息
   */
  geocoder: function(address) {
    let that = this
    if (!address) {
      console.log(`地址为空，不进行操作了！！！！` + address)
      return;
    }
    qqMapWxUtil.geocoder(address).then(response => {
      that.reverseGeocoder(response.result.location.lat, response.result.location.lng)
    })
  },
  /**
   * 下拉触发
   */
  bindRegionChange: function(e) {
    let that = this
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
    let address = e.detail.value[0] + e.detail.value[1] + e.detail.value[2]
    console.log(`获取到的地址是：` + address)

    that.geocoder(address)
  },
  /**
   * 图片预览
   */
  queryImg: function(e) {
    let urls = [];
    urls.push(e.target.dataset.list)
    wx.previewImage({
      urls: urls,
      success: function(res) {
        console.log("成功了")
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})